﻿using Networks.Handlers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;

namespace Networks
{
    public class BroadcastFactory
    {
        public const string IS_EVT_KEY_NAME = "__evt_";

        private static Dictionary<string, Action<JObject>> _callbacks = new Dictionary<string, Action<JObject>>();
        public static Dictionary<string, Action<JObject>> Callbacks { get => _callbacks; }

        public static void RegistEvents()
        {
            _callbacks.Add(Routes.LOBBY_NOTIFY_ADD, GameHandler.onAdd);
            _callbacks.Add(Routes.LOBBY_NOTIFY_LEAVE, GameHandler.onLeave);
            _callbacks.Add(Routes.LOBBY_NOTIFY_CHAT, GameHandler.onChat);

            _callbacks.Add(Routes.ROOM_NOTIFY_STATE_CHANGFE, GameHandler.onRoomStateChange);
            _callbacks.Add(Routes.ROOM_NOTIFY_PLAYER_LEAVE, GameHandler.onPlayerLeave);

            _callbacks.Add(Routes.ROOM_NOTIFY_PLAYER_INFO, GameHandler.updatePlayerInfo);
            _callbacks.Add(Routes.ROOM_NOTIFY_PLAYER_STATE, GameHandler.updatePlayerState);

            _callbacks.Add(Routes.S2C_GAME_LOAD, GameHandler.onGameLoading);
            _callbacks.Add(Routes.S2C_GAME_BEGIN, GameHandler.onGameBegin);

            _callbacks.Add(Routes.GAME_NOTIFY_ENTER_FRAME, GameHandler.onEnterFrame);
        }

        public static void InvokeHandle(string route, JObject data)
        {
            Action<JObject> handler;
            _callbacks.TryGetValue(route, out handler);
            if (handler != null)
            {
                handler(data);
            }
            else
            {
                Debug.LogWarning("cannot find handler for " + route);
            }
        }
    }
}